package com.hefan.oms.dao;

import com.alibaba.fastjson.JSON;
import com.hefan.common.exception.DataIllegalException;
import com.hefan.common.orm.dao.BaseDaoImpl;
import com.hefan.oms.bean.WebUserExpend;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by hbchen on 2016/10/8.
 */
@Repository
public class ExpendDao extends BaseDaoImpl<WebUserExpend> {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public long insertNewRecord(WebUserExpend record) throws Exception{

        record = super.save(record);
        if(record.getId()<=0){
            throw new DataIllegalException(String.format("保存用户支出失败%s", JSON.toJSONString(record)));
        }
        return record.getId();

    }

    /**
     * 获取用户某一时间段消费的饭票合计
     * @param userId
     * @param beginDate
     * @param endDate
     * @return
     */
    public long findUserExpendFanpiao(String userId, Date beginDate, Date endDate) {
        String sql = "select sum(fanpiao_num) as fanpiaoTotal from web_user_expend where user_id=? and create_time between ? and ?";
        Long total = this.getJdbcTemplate().queryForObject(sql,new Object[] {userId,beginDate,endDate},Long.class);
        if(total ==  null) {
            return 0L;
        }
        return total.longValue();
    }
}
